﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using SocialApi.Core.Extensions;

namespace SocialApi.Instagram.AppSettings
{
    /// <summary>
    /// Настройки приложения
    /// </summary>
    public sealed class Settings
    {
        /// <summary>
        /// Значение настройки
        /// </summary>
        public string Value { get; private set; }

        /// <summary>
        /// Стандартные настройки приложения
        /// </summary>
        public static readonly Settings Basic = new Settings("basic");

        /// <summary>
        /// Доступ к комментариям
        /// </summary>
        public static readonly Settings Comments = new Settings("comments");

        /// <summary>
        /// Доступ к друзям
        /// </summary>
        public static readonly Settings Relationships = new Settings("relationships");

        /// <summary>
        /// Доступ к лайкам
        /// </summary>
        public static readonly Settings Likes = new Settings("likes");

        /// <summary>
        /// Все настройки приложения
        /// </summary>
        public static readonly Settings All = Basic | Comments | Relationships | Likes;

        private readonly ICollection<Settings> _settingses;

        private Settings(string value)
        {
            Value = value;
        }

        private Settings(Settings p1, Settings p2)
        {
            _settingses = new Collection<Settings>();
            Add(p1);
            Add(p2);
        }

        private void Add(Settings setting)
        {
            if (setting._settingses.Exists())
            {
                if (setting._settingses.Count.Exists())
                {
                    foreach (var settings in setting._settingses.Where(settings => _settingses.All(s => s.Value != settings.Value)))
                    {
                        _settingses.Add(settings);
                    }
                }

            }
            else
            {
                if (_settingses.All(s => s.Value != setting.Value))
                {
                    _settingses.Add(setting);
                }
            }
        }

        public static Settings operator |(Settings p1, Settings p2)
        {
            return new Settings(p1, p2);
        }
        
        public override string ToString()
        {
            if (!_settingses.Exists() || !_settingses.Count.Exists())
            {
                return Value;
            }
#if NET_4_5 || NET_4_0
            return string.Join("+", _settingses);
#else
            return string.Join("+", _settingses.Select(settings => settings.Value).ToArray());
#endif
        }
    }
}